const { authManager } = require('../../../utils/auth');
Page({
  data:{
    avatarUrl:'/images/default-avatar.png',
    userInfo:{},
    form:{ displayName:'', mobile:'', email:'', notify:'on' },
    displayDepartmentName:''
  },
  onLoad(){
    if(!authManager.pageLoginCheck()) return;
    this.loadUserInfo()
  },
  onShow(){
    if(!authManager.pageLoginCheck()) return;
    this.loadUserInfo()
  },
  loadUserInfo(){
    try{
      const user=wx.getStorageSync('user_info')||{}
      const dept=this.getDepartmentName(user.part_id_id)
      this.setData({
        userInfo:user,
        avatarUrl: user.wx_avatar_url || '/images/default-avatar.png',
        form:{
          displayName: user.zh_name || '',
          mobile: user.mobile || '',
          email: user.email || '',
          notify: (user.notify==='off')? 'off':'on'
        },
        displayDepartmentName: dept || '未知部门'
      })
    }catch(e){console.error(e)}
  },
  getDepartmentName(partId){
    const departments={1:'总裁办',2:'信息技术部',3:'商务服务部',4:'计划财务部',5:'行政人事部',6:'分公司管理部',7:'规划设计中心',8:'数据勘测中心',9:'资源评价中心',10:'评估咨询一中心',11:'评估咨询二中心',12:'经纪代理中心',13:'江阴事业中心',14:'南京事业中心',15:'其它'}
    return departments[partId] || '未知部门'
  },
  onInput(e){
    const id=e.currentTarget.dataset.id
    const value=e.detail.value
    this.setData({ [`form.${id}`]: value })
  },
  onPrefChange(e){
    const key=e.currentTarget.dataset.id
    const v=e.detail.current
    this.setData({ [`form.${key}`]: v })
  },
  onChooseAvatar(e){
    const avatarUrl=e.detail.avatarUrl
    this.setData({ avatarUrl })
    const u=this.data.userInfo
    wx.uploadFile({
      formData:{ user_id:u.id, user_name:u.zh_name, user_openid:u.open_id },
      filePath: avatarUrl,
      name:'avatarImg',
      url:`${getApp().globalData.serverUrl}/wx_UpdateUseravatar/`,
      success:(res)=>{ try{ const result=JSON.parse(res.data); if(result.success){ wx.showToast({title:'头像已更新'}); } else { wx.showToast({title:result.message,icon:'none'}) } }catch(err){ wx.showToast({title:'头像更新失败',icon:'none'}) } },
      fail:()=>wx.showToast({title:'网络错误',icon:'none'})
    })
  },
  onReset(){ this.loadUserInfo() },
  onSave(){
    const data={ ...this.data.userInfo, zh_name:this.data.form.displayName, mobile:this.data.form.mobile, email:this.data.form.email, notify:this.data.form.notify }
    wx.setStorageSync('user_info', data)
    wx.showToast({title:'已保存',icon:'success'})
  },
  // 以下设置动作沿用 profile.js 的功能
  handleClearCache(){ getCurrentPages().find(p=>p.route.endsWith('profile/profile'))?.performClearCache?.(); },
  handleLogout(){ authManager.logout() },
  bandwx(){ getCurrentPages().find(p=>p.route.endsWith('profile/profile'))?.bandwx?.() },
  handleChangePassword(){ getCurrentPages().find(p=>p.route.endsWith('profile/profile'))?.handleChangePassword?.() }
})
